package com.yiboshi.rehrs.job;

import cn.hutool.core.util.RuntimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.model.TaskHostInfo;
import com.yiboshi.rehrs.domain.service.IZhongOrderService;
import com.yiboshi.rehrs.domain.service.IZhongUserImageService;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.helper.*;
import com.yiboshi.rehrs.manager.IptablesManager;
import com.yiboshi.rehrs.manager.SmurfsManager;
import com.yiboshi.rehrs.manager.ZhongYouManager;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author jack 2025/3/21
 */

@Component
@Slf4j
public class SystemJob {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedisHelper redisHelper;
    @Autowired
    ProxyHelper proxyHelper;

    @Autowired
    HelperDaxiang helperDaxiang;

    @Autowired
    IZhongUserService zhongUserService;
    @Autowired
    IZhongUserImageService zhongUserImageService;
    @Autowired
    ZhongYouManager zhongYouManager;

    @Autowired
    RedisLocker redisLocker;

    @Autowired
    LimitHelper limitHelper;

    @Autowired
    IZhongOrderService zhongOrderService;

    @Autowired
    SmurfsManager smurfsManager;

    @Value("${zhong.monitor.warnConnections:400}")
    private Integer warnConnections;


    @Value("${zhong.monitor.stopConnections:600}")
    private Integer stopConnections;

    @Value("${zhong.monitor.enable:false}")
    private boolean monitorEnable;



    @Scheduled(cron = "0/3 * * * * ?")//0 0 0/1 * * ?
    public void loadProxyByApi() throws Exception {
        if (StrUtils.isBlank(RehrsSystemConfig.getProfile())) {
            return;
        }
        int hour = LocalDateTime.now().getHour();
        //log.info("loadProxyByApi");
        if(hour>=5&&hour<=23){
            //monitor未开启说明是对外的服务
            proxyHelper.remove();
            proxyHelper.loadProxyByApi();
        }
    }

    @Scheduled(cron = "0/20 * * * * ?")//0 0 0/1 * * ?
    public void monitorByNginxJob() throws Exception {
        try{
            monitorByNginx();
        }catch (Exception e){
            log.error("",e);
        }
        //订单处理
        smurfsManager.orderTask();
    }


    @Scheduled(cron = "0 0 0,2 * * ?") // 每天 0 点和 1 点执行
    public void midnightTask() {
        if (StrUtils.isBlank(RehrsSystemConfig.getProfile())) {
            return;
        }
        // 添加你的业务逻辑
        log.info("nauth任务执行: {}", LocalDateTime.now());
        if(LocalDateTime.now().getHour()==2){
            LimitHelper.ALL_NAUTH_SET.clear();
        }
        LimitHelper.putNAuth();




    }



    @Scheduled(cron = "0 */2 * * * ?")//0 0 0/1 * * ?
    public void run() throws Exception {
        if (StrUtils.isBlank(RehrsSystemConfig.getProfile())) {
            return;
        }
        taskMonitor();
        initTraceQueryInfo();
       checkDaxiangModeAndToken();

        // addPort();

    }

    private void checkDaxiangModeAndToken() {
        int hour = LocalDateTime.now().getHour();
        if(hour>=0&&hour<=5){
            return;
        }
        boolean b = redisLocker.tryLock("daxiang-vip-token-new", 20);
        if(b){
            //大象vip账号     token有效性检测
            Boolean member = stringRedisTemplate.opsForSet().isMember(VarConstant.enble_helper_mode, "2");
            if(!member){
                ZhongUser zhongUser = helperDaxiang.getModeVipUser(false);
                if(zhongUser!=null){
                    stringRedisTemplate.opsForSet().add(VarConstant.enble_helper_mode,"2");
                }
            }else{
                //快过期就重新登录
                String s = helperDaxiang.vipTokenKey();
                Long expire = stringRedisTemplate.getExpire(s,TimeUnit.SECONDS);
                if(expire<(120+AperStringUtils.randomNum(60))){//快过期了
                    ZhongUser zhongUser = helperDaxiang.getModeVipUser(false);
                    if(zhongUser==null){
                        stringRedisTemplate.opsForSet().remove(VarConstant.enble_helper_mode,"2");
                    }
                }

            }
        }
    }

    private void monitorByNginx() throws Exception {
        if(!monitorEnable){
            return;
        }
       /* //尝试恢复
        boolean isClose = Objects.equals("1",stringRedisTemplate.opsForValue().get("close-app"));
        if(isClose){
            boolean success = redisLocker.tryLock("open-app", 100);
            if(success){
                //开启80端口
                boolean ok = IptablesManager.openPort80();
                if(ok){
                    stringRedisTemplate.delete("close-app");
                    //开启80端口
                    redisLocker.delLock("close-app");
                    DingdingUtils.sendMessageByLocal("已恢复APP访问","");
                }else{
                    log.error("开启80端口失败");
                }
            }
            return;
        }*/
        OkHttpUtil okHttpUtil = new OkHttpUtil().url("http://127.0.0.1/nginx_status_110").get();
        String execute = okHttpUtil.execute();
        JSONObject jsonObject = JSONObject.parseObject(execute);
        JSONObject connections = jsonObject.getJSONObject("connections");
        long active = connections.getLong("active");

        if(active>warnConnections){//600
            boolean success = redisLocker.tryLock("attack-notice", 1800);
            if(success){
                DingdingUtils.sendMessageByLocal("服务器连接数量过大,可能被攻击了.active="+active,"");
            }
            //连接数
        }
        /*if(active>stopConnections){//1200
            boolean success = redisLocker.tryLock("close-app", 3600);
            if(success){
                boolean ok = IptablesManager.closePort80();
                if(ok){
                    //关闭80端口
                    stringRedisTemplate.opsForValue().set("close-app","1");
                    redisLocker.tryLock("open-app", 100);
                    DingdingUtils.sendMessageByLocal("已关闭APP访问","");
                }else{
                    log.error("关闭80端口失败");
                }


            }
        }*/

        //boolean success = redisLocker.delLock("close-app");



    }



    private void initTraceQueryInfo() {
        LocalDateTime localDateTime = LocalDateTime.now();
        int hour = localDateTime.getHour();
        if(hour>=9&&hour<=21){
            ZhongUser sunLogonUser = zhongYouManager.initTraceQueryInfo();
        }
    }

    private void taskMonitor() {
        TaskHostInfo taskHostInfo = redisHelper.loadTaskHostInfo(false);
        String key = taskHostInfo.getKey();
        taskHostInfo.setHeartbeatTimeStr(DateUtils.dateTimeToStr(LocalDateTime.now(),DateUtils.SQL_TIME));
        String order = taskHostInfo.getOrder();
        if(order.equals("1")){
            //重启
            taskHostInfo.setOrder("0");
        }
        redisHelper.saveTaskHostInfo(taskHostInfo);
        if(order.equals("1")) {
            String restart = taskHostInfo.getRestart();
            if (StrUtils.isNotBlank(restart)) {
                log.info("task host key :{} restart", key);
                RuntimeUtil.exec(restart);
            } else {
                log.error("task host key :{} restart is null");
            }
        }

        if(!AperStringUtils.isWindows){
            // //date -s "$(curl -sI https://www.baidu.com | grep -i "Date: " | cut -d' ' -f2-)" 校准时间
            try{
                RuntimeUtil.exec("date -s \"$(curl -sI https://www.baidu.com | grep -i \"Date: \" | cut -d' ' -f2-)\"");
            }catch (Exception e){
                log.error("",e);
            }
        }
    }
}
